//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
using DotNetNuke.Security.Membership;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
namespace DotNetNuke.Modules.Admin.Users
{
	partial class User : UserUserControlBase
	{
		public bool IsValid
		{
			get { return Validate(); }
		}
		public bool ShowPassword
		{
			get { return tblPassword.Visible; }
			set { tblPassword.Visible = value; }
		}
		public bool ShowUpdate
		{
			get { return pnlUpdate.Visible; }
			set { pnlUpdate.Visible = value; }
		}
		private void UpdateDisplayName()
		{
			object setting = UserModuleBase.GetSetting(UserPortalID, "Security_DisplayNameFormat");
			if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting))))
			{
				User.UpdateDisplayName(Convert.ToString(setting));
			}
		}
		private bool Validate()
		{
			bool _IsValid = true;
			if (_IsValid)
			{
				_IsValid = UserEditor.IsValid;
			}
			if (AddUser && ShowPassword)
			{
				UserCreateStatus createStatus = UserCreateStatus.AddUser;
				if (!chkRandom.Checked)
				{
					if (txtPassword.Text != txtConfirm.Text)
					{
						createStatus = UserCreateStatus.PasswordMismatch;
					}
					if (createStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(txtPassword.Text))
					{
						createStatus = UserCreateStatus.InvalidPassword;
					}
					if (createStatus == UserCreateStatus.AddUser)
					{
						User.Membership.Password = txtPassword.Text;
					}
				}
				else
				{
					User.Membership.Password = UserController.GeneratePassword();
				}
				if (createStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer)
				{
					if (string.IsNullOrEmpty(txtQuestion.Text))
					{
						createStatus = UserCreateStatus.InvalidQuestion;
					}
					else
					{
						User.Membership.PasswordQuestion = txtQuestion.Text;
					}
					if (createStatus == UserCreateStatus.AddUser)
					{
						if (string.IsNullOrEmpty(txtAnswer.Text))
						{
							createStatus = UserCreateStatus.InvalidAnswer;
						}
						else
						{
							User.Membership.PasswordAnswer = txtAnswer.Text;
						}
					}
				}
				if (createStatus != UserCreateStatus.AddUser)
				{
					_IsValid = false;
					valPassword.ErrorMessage = "<br/>" + UserController.GetUserCreateStatus(createStatus);
					valPassword.IsValid = false;
				}
			}
			return _IsValid;
		}
		public void CreateUser()
		{
			UpdateDisplayName();
			if (IsRegister)
			{
				if (PortalSettings.UserRegistration == (int)DotNetNuke.Common.Globals.PortalRegistrationType.PublicRegistration)
				{
					User.Membership.Approved = true;
				}
				else
				{
					User.Membership.Approved = false;
				}
			}
			else
			{
				User.Membership.Approved = chkAuthorize.Checked;
			}
			UserInfo user = User;
			UserCreateStatus createStatus = UserController.CreateUser(ref user);
			UserCreatedEventArgs args;
			if (createStatus == UserCreateStatus.Success)
			{
				args = new UserCreatedEventArgs(User);
				args.Notify = chkNotify.Checked;
			}
			else
			{
				args = new UserCreatedEventArgs(null);
			}
			args.CreateStatus = createStatus;
			OnUserCreated(args);
			OnUserCreateCompleted(args);
		}
		public override void DataBind()
		{
			if (Page.IsPostBack == false)
			{
				string confirmString = Localization.GetString("DeleteItem");
				if (IsUser)
				{
					confirmString = Localization.GetString("ConfirmUnRegister", this.LocalResourceFile);
				}
				ClientAPI.AddButtonConfirm(cmdDelete, confirmString);
				chkRandom.Checked = false;
			}
			cmdDelete.Visible = false;
			cmdRemove.Visible = false;
			cmdRestore.Visible = false;
			if (!AddUser)
			{
				bool DeletePermitted = !(User.UserID == PortalSettings.AdministratorId) && !(IsUser && User.IsSuperUser);
				if ((DeletePermitted))
				{
					if ((User.IsDeleted))
					{
						cmdRemove.Visible = true;
						cmdRestore.Visible = true;
					}
					else
					{
						cmdDelete.Visible = true;
					}
				}
			}
			if (IsUser)
			{
				cmdDelete.ResourceKey = "UnRegister";
			}
			else
			{
				cmdDelete.ResourceKey = "Delete";
			}
			if (AddUser)
			{
				pnlAddUser.Visible = true;
				if (IsRegister)
				{
					tblAddUser.Visible = false;
					trRandom.Visible = false;
					if (ShowPassword)
					{
						trQuestion.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer;
						trAnswer.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer;
						lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", this.LocalResourceFile);
					}
				}
				else
				{
					lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", this.LocalResourceFile);
				}
				txtConfirm.Attributes.Add("value", txtConfirm.Text);
				txtPassword.Attributes.Add("value", txtPassword.Text);
			}
			UserEditor.DataSource = User;
			UserEditor.DataBind();
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			PageBase basePage = this.Page as PageBase;
			if (basePage != null)
			{
				if (basePage.PageCulture.TextInfo.IsRightToLeft)
				{
					UserEditor.LabelMode = LabelMode.Right;
				}
				else
				{
					UserEditor.LabelMode = LabelMode.Left;
				}
			}

			cmdDelete.Click += new EventHandler(cmdDelete_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
			cmdRemove.Click += new EventHandler(cmdRemove_Click);
			cmdRestore.Click += new EventHandler(cmdRestore_Click);
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			UserEditor.LocalResourceFile = this.LocalResourceFile;
			
		}
		private void cmdDelete_Click(System.Object sender, System.EventArgs e)
		{
			string name = User.Username;
			int id = UserId;
			UserInfo user = User;
			if (UserController.DeleteUser(ref user, true, false))
			{
				OnUserDeleted(new UserDeletedEventArgs(id, name));
			}
			else
			{
				OnUserDeleteError(new UserUpdateErrorArgs(id, name, "UserDeleteError"));
			}
		}

		/// -----------------------------------------------------------------------------
		/// <summary>
		/// cmdRestore_Click runs when the restore Button is clicked
		/// </summary>
		/// <history>
		/// 	[aprasad]	02/15/2011  Created
		/// </history>
		/// -----------------------------------------------------------------------------
		private void cmdRestore_Click(System.Object sender, System.EventArgs e)
		{
			string name = User.Username;
			int id = UserId;

			if (UserController.RestoreUser(User))
			{
				OnUserRestored(new UserRestoredEventArgs(id, name));
			}
			else
			{
				OnUserRestoreError(new UserUpdateErrorArgs(id, name, "UserRestoreError"));
			}
		}

		/// -----------------------------------------------------------------------------
		/// <summary>
		/// cmdRemove_Click runs when the remove Button is clicked
		/// </summary>
		/// <history>
		/// 	[aprasad]	02/15/2011  Created
		/// </history>
		/// -----------------------------------------------------------------------------
		private void cmdRemove_Click(System.Object sender, System.EventArgs e)
		{
			string name = User.Username;
			int id = UserId;

			if (UserController.RemoveUser(User))
			{
				OnUserRemoved(new UserRemovedEventArgs(id, name));
			}
			else
			{
				OnUserRemoveError(new UserUpdateErrorArgs(id, name, "UserRemoveError"));
			}
		}

		private void cmdUpdate_Click(System.Object sender, System.EventArgs e)
		{
			if (AddUser)
			{
				if (IsValid)
				{
					CreateUser();
				}
			}
			else
			{
				if (UserEditor.IsValid && UserEditor.IsDirty && (User != null))
				{
					if (User.UserID == PortalSettings.AdministratorId)
					{
						DotNetNuke.Common.Utilities.DataCache.ClearPortalCache(UserPortalID, false);
					}
					try
					{
						UpdateDisplayName();
						UserController.UpdateUser(UserPortalID, User);
						OnUserUpdated(EventArgs.Empty);
						OnUserUpdateCompleted(EventArgs.Empty);
					}
					catch (Exception ex)
					{
						UserUpdateErrorArgs args = new UserUpdateErrorArgs(User.UserID, User.Username, "EmailError");
						OnUserUpdateError(args);
					}
				}
			}
		}
		protected void UserEditorCreated(object sender, UI.WebControls.PropertyEditorItemEventArgs e)
		{
			object setting = null;
			switch (e.Editor.Name.ToLower())
			{
				case "displayname":
					setting = UserModuleBase.GetSetting(UserPortalID, "Security_DisplayNameFormat");
					if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting))))
					{
						if (AddUser)
						{
							e.Editor.Visible = false;
						}
						else
						{
							e.Editor.EditMode = PropertyEditorMode.View;
						}
					}
					break;
				case "email":
					setting = UserModuleBase.GetSetting(UserPortalID, "Security_EmailValidation");
					if ((setting != null) && (!string.IsNullOrEmpty(Convert.ToString(setting))))
					{
						e.Editor.ValidationExpression = Convert.ToString(setting);
					}
					break;
			}
		}
	}
}
